import ajax from 'superagent';
import CONST from '../commons/const';

export const REQUEST_POST = 'REQUEST_POST';
export const RECEIVE_POST = 'RECEIVE_POST';
export const TEST_ACTION = 'TEST_ACTION';
export const CHANGE_MENU_SELECTED = 'CHANGE_MENU_SELECTED';
export const TOGGLE_MENU = 'TOGGLE_MENU';
export const BEFORE_REQUEST_POST = 'BEFORE_REQUEST_POST';

// 获取数据前
const beforeRequestPost = url => ({
  type: BEFORE_REQUEST_POST,
  url,
});

/* eslint-disable no-unused-vars */
// 开始获取数据
const requestPost = url => ({
  type: REQUEST_POST,
  url,
});
/* eslint-enable */
// 获取数据成功
const receivePost = (url, data) => ({
  type: RECEIVE_POST,
  url,
  data,
});

// 页面初次渲染时获取数据
export const fetchDatas = (url, params = {}) => dispatch => {
  dispatch(beforeRequestPost(url));
  ajax
    .get(url)
    .query(params)
    .then(res => {
      if (res.status === 200) {
        dispatch(receivePost(url, res.body));
      }
    });
};

// 返回一个介于min和max之间的随机数
const getRandomArbitrary = (min, max) => (Math.random() * (max - min)) + min;

let timer;
// 循环获取数据 --- 长轮询
export const circleFetchDatas = (url, params = {}) => dispatch => {
  clearTimeout(timer);
  dispatch(beforeRequestPost(url));
  const timeStart = Date.now();
  ajax
    .get(url)
    .query(params)
    .then(res => {
      const timeEnd = Date.now();
      const differenceTime = timeEnd - timeStart;
      // console.log(differenceTime);
      if (res.status === 200) {
        dispatch(receivePost(url, res.body));
        const newParams = {
          'synced-issue': res.body.data[0].issue,
        };
        if (differenceTime < CONST.TIME_LIMIT) {
          timer = setTimeout(() => {
            dispatch(circleFetchDatas(url, newParams));
          }, (CONST.TIME_LIMIT - differenceTime) + getRandomArbitrary(0, 2000));
        } else {
          dispatch(circleFetchDatas(url, newParams));
        }
      } else {
        dispatch(circleFetchDatas(url, params));
      }
    });
};

export const testAction = (data) => ({
  type: TEST_ACTION,
  data,
});

export const toggleMenu = (data) => ({
  type: TOGGLE_MENU,
  data,
});

export const changeMenuSelected = (index) => ({
  type: CHANGE_MENU_SELECTED,
  index,
});
